package ws

import (
	"encoding/json"
	"fmt"
)

//FeatureActionsMgr ws操作事件管理器
type FeatureActionsMgr struct {
	actions map[string]IActionEvent
}

func NewFeatureActionsMgr(actions ...IActionEvent) *FeatureActionsMgr {
	actionMap := make(map[string]IActionEvent)

	for _, v := range actions {
		actionMap[v.Name()] = v
	}

	return &FeatureActionsMgr{
		actions: actionMap,
	}
}

//Parse 解析数据，数据格式满足一下
func (mgr *FeatureActionsMgr) Parse(data []byte) (IActionEvent, error) {
	m := make(map[string]interface{}, 1)

	if err := json.Unmarshal(data, &m); err != nil {
		return nil, err
	}

	//logger.Info("%s,%v", string(data), m)
	if name, exist := m["action"]; exist {
		return mgr.GetAction(name.(string))
	}

	return nil, fmt.Errorf("action not support")
}

//ParseDo 解析数据并且执行
func (mgr *FeatureActionsMgr) ParseDo(client *Client, data []byte) (IActionEvent, error) {
	act, err := mgr.Parse(data)
	if err != nil {
		return nil, err
	}
	act.Do(client, data)
	return act, nil
}

//GetAction 获取对应action
func (mgr *FeatureActionsMgr) GetAction(name string) (IActionEvent, error) {
	if mgr.actions[name] == nil {
		return nil, fmt.Errorf("action not support %s", name)
	}

	return mgr.actions[name], nil
}
